package cn.wolfcode.luowowo.website.web.controller;


import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisVOService;
import cn.wolfcode.luowowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("travel")
public class TravelController {

    @Reference
    private ITravelService travelService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private ITravelCommentService travelCommentService;

    @Reference
    private ITravelStatisVOService travelStatisVOService;

    @Value("${file.path}")
    private String filePath;

    /**
     * 显示旅游日记主页
     * @param model
     * @param qo
     * @return
     */
    @RequestMapping("")
    public String list(Model model, @ModelAttribute("qo")TravelQuery qo) {
        //pageInfo
        model.addAttribute("pageInfo", travelService.query(qo));

        //details 查询攻略前五
        List<StrategyDetail> details = strategyDetailService.getTop5();
        model.addAttribute("details",details);

        return "travel/list";
    }

    /**
     * 跳转编辑页面
     * @param model
     * @return
     */
    @RequestMapping("/input")
    public String input(Model model, Long id) {
        //dests
        List<Destination> list = destinationService.list();
        model.addAttribute("dests",list);

        //回显游记内容
        if (id != null) {
            Travel travel = travelService.get(id);
            travel.setTravelContent(travelService.getContent(id));
            model.addAttribute("tv", travel);
        }

        return "travel/input";
    }


    /**
     * 游记保存或修改操作
     * @param travel
     * @param userInfo
     * @return
     */
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, @UserParam UserInfo userInfo) {
        travel.setAuthor(userInfo);
        Long id = travelService.saveOrUpdate(travel);
        return AjaxResult.success().addData(id);
    }

    /**
     * 显示攻略文章内容
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/detail")
    public String detail(Model model,Long id, @UserParam UserInfo userInfo) {
        //detail
        Travel travel = travelService.get(id);
        travel.setTravelContent(travelService.getContent(id));
        model.addAttribute("detail", travel);

        //如果用户user不为null,并且用户id用游记的作者id相等,那么就返回true
        model.addAttribute("flag",userInfo != null && travel.getAuthor().getId() == userInfo.getId());

        //toasts
        //面包屑查询
        List<Destination> toasts = destinationService.getToasts(travel.getDest().getId());
        Destination dest = toasts.remove(toasts.size() - 1);
        model.addAttribute("toasts", toasts);
        model.addAttribute("dest", dest);

        //sds
        model.addAttribute("sds",strategyDetailService.getTop3());

        //ts
        model.addAttribute("ts", travelService.getTop3());

        //增加浏览数
        travelStatisVOService.increaseViewnum(id, 1);

        //获取vo对象
        TravelStatisVO vo = travelStatisVOService.getTravelStatisVO(id);
        model.addAttribute("vo", vo);

        //isFavor 判断用户是否收藏
        boolean isFavor = false;
        if (userInfo != null) {
             isFavor = travelStatisVOService.isFavor(userInfo.getId(), id);
        }
        model.addAttribute("isFavor", isFavor);

        //list  显示出游记的评论表
        TravelCommentQuery query = new TravelCommentQuery();
        query.setTravelId(travel.getId());
        query.setCurrentPage(1);
        query.setPageSize(Integer.MAX_VALUE);   //不需要分页,所以设置最大值即可查询全部评论
        Page page = travelCommentService.query(query);
        model.addAttribute("list", page.getContent());

        return "travel/detail";
    }

    //添加评论
    @RequestMapping("/commentAdd")
    public String commentAdd(Model model, TravelComment travelComment, @UserParam UserInfo userInfo, Long floor) {
        //c   评论
        travelComment.setUserId(userInfo.getId());
        travelComment.setUsername(userInfo.getNickname());
        travelComment.setCity(userInfo.getCity());
        travelComment.setLevel(userInfo.getLevel());
        travelComment.setHeadUrl(userInfo.getHeadImgUrl());

        TravelComment comment = travelCommentService.save(travelComment);
        model.addAttribute("c", comment);


        //floor   楼层  不需要加一!!!! 因为查询的时候评论已经存进去了
        model.addAttribute("floor", travelCommentService.getCount(travelComment.getTravelId()));

        return "travel/commentTpl";
    }

    //顶
    @RequestMapping("/travelThumbup")
    @ResponseBody
    public Object travelThumbup(Long tid, @UserParam UserInfo userInfo) {
        if (userInfo == null) {
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.setMsg("登录后可进行顶操作");
            ajaxResult.setSuccess(false);
            ajaxResult.setCode(102);
            return ajaxResult;
        }

        //顶操作
        //flag判断是否顶成功(也就是第一次还是第n次顶)
        boolean flag = travelStatisVOService.increaseThumbup(tid, userInfo.getId());

        //获取travelVo对象
        TravelStatisVO travelStatisVO = travelStatisVOService.getTravelStatisVO(tid);

        if (flag) {
            return new AjaxResult(flag).addData(travelStatisVO);
        } else {
            return new AjaxResult(flag);
        }
    }


    //收藏
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long tid, @UserParam UserInfo userInfo) {
        if (userInfo == null) {
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.setMsg("登录后可进行收藏操作");
            ajaxResult.setSuccess(false);
            ajaxResult.setCode(102);
            return ajaxResult;
        }

       //收藏
        //根据flag,判断是取消收藏还是添加收藏
        boolean flag = travelStatisVOService.increaseFavor(tid, userInfo.getId());

        //获取travelVo对象
        TravelStatisVO travelStatisVO = travelStatisVOService.getTravelStatisVO(tid);

        return new AjaxResult(flag).addData(travelStatisVO);
    }


    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }
}
